package cn.qicaiwang.open.app.server.Impl;

import cn.qicaiwang.open.app.entity.AdmissionCard;
import cn.qicaiwang.open.app.server.PdfCustomService;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**

 @since 2021/7/11 16:12
 */
@Service
@Slf4j
public class PdfCustomServiceImpl implements PdfCustomService {

    @Override
    public void generatorAdmissionCard(AdmissionCard admissionCard, HttpServletResponse response) throws UnsupportedEncodingException, FileNotFoundException {
    // 模板名称
        String templateName = "管辖异议申请书.pdf";
        String path = "";
    // 获取操作系统名称，根据系统名称确定模板存放的路径
        String systemName = System.getProperty("os.name");
        if (systemName.toUpperCase().startsWith("WIN")) {
            path = "F:/pdf/";
        } else {
            path = "/usr/local/pdf/";
        }


        // 生成导出PDF的文件名称
        String fileName = admissionCard.getName() + "-建造师准考证.pdf";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

        // 设置响应头
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);

        OutputStream out = null;
        ByteArrayOutputStream bos = null;
        PdfStamper stamper = null;
        PdfReader reader = null;

        try {
            // 读取PDF模板表单
            reader = new PdfReader(path + templateName);
            bos = new ByteArrayOutputStream();

            // 根据模板表单生成一个新的PDF
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();

            // 设置中文字体
            BaseFont font = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            form.addSubstitutionFont(font);

            // 装配数据
            Map<String, Object> data = new HashMap<>(15);
            data.put("no", admissionCard.getNo());
            data.put("name", admissionCard.getName());
            data.put("sex", admissionCard.getSex());
            data.put("idCard", admissionCard.getIdCard());
            data.put("school", admissionCard.getSchool());
            data.put("enterSchool", admissionCard.getEnterSchool());
            data.put("examAddress", admissionCard.getExamAddress());
            data.put("major", admissionCard.getMajor());
            data.put("enterName", admissionCard.getEnterName());

            // 设置表单数据
            for (String key : data.keySet()) {
                form.setField(key, data.get(key).toString());
            }

            // 设置PDF不可修改
            stamper.setFormFlattening(true);
            stamper.close();

            // 获取生成的PDF字节数组
            byte[] pdfBytes = bos.toByteArray();

            // 1. 输出到浏览器
            out = response.getOutputStream();
            out.write(pdfBytes);
            out.flush();

            // 2. 保存到服务器本地
            String savePath = path + "generated/" + fileName;
            File saveDir = new File(path + "generated/");
            if (!saveDir.exists()) {
                saveDir.mkdirs();
            }

            try (FileOutputStream fileOut = new FileOutputStream(savePath)) {
                fileOut.write(pdfBytes);
                log.info("PDF已保存到服务器本地: {}", savePath);
            } catch (IOException e) {
                log.error("本地保存失败", e);
            }

            log.info("PDF导出成功，文件名: {}", fileName);

        } catch (Exception e) {
            log.error("生成PDF失败", e);
            throw new RuntimeException("生成PDF失败", e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (bos != null) {
                    bos.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (Exception e) {
                log.error("关闭资源失败", e);
            }
        }
    }
}
